
import { iotLogupdate } from "@/api/bedList";
import { mapGetters } from "vuex"
// const audio1596 = require('../assets/mp3/1596.mp3')
// const audio5196 = require('../assets/mp3/5196.mp3')
// const audio8069 = require('../assets/mp3/8069.mp3')
// const audio10686 = require('../assets/mp3/10686.mp3')
export default {
  data() {
    return{
      // webSocket对象
      webNewSocket: null,
      // webNewSocketUrl地址
      webNewSocketUrl: "wss://device.yiyanglao.com.cn:9002",
      //连贯标识 防止反复连贯
      isNewConnect: false,
      //断线重连后，提早5秒从新创立WebSocket连贯  recnew用来存储提早申请的代码
      recnew: null,
      //每段时间发送一次心跳包 这里设置为20s
      timeout: 20000,
      //延时发送音讯对象（启动心跳新建这个对象，收到音讯后重置对象）
      timeoutObj: null,
      checkMsg: "发送数据"
    }
  },
  computed: {

  },
  mounted() {
    // if(getAccessToken()){
    //   if(typeof(WebSocket) === "undefined"){
    //     alert("您的浏览器不支持WebSocket")
    //     return false
    //   }
    //   if(!this.webNewSocket){
    //     this.createNewWebSocket();
    //   } else {
    //     this.webNewSocket.close();
    //   }
    //   // this.audio = new Audio();
    // }
  },
  methods: {
    //创立webSocket连贯
    createNewWebSocket() {
      let that = this;
      try {
        if ("WebSocket" in window) {
          that.webNewSocket = new WebSocket(that.webNewSocketUrl);
        } else if ("MozWebSocket" in window) {
          that.webNewSocket = new MozWebSocket(that.webNewSocketUrl);
        }
        that.initNewWebsocket();
      } catch (e) {
      }

    },
    //初始化webNewSocket连贯
    initNewWebsocket() {
      let that = this;
      //webNewSocket连贯建设之后会调用onopen办法
      that.webNewSocket.onopen = that.newwebsocketonopen;
      //当websocket收到服务器发送的信息之后  会调用onmessage办法
      that.webNewSocket.onmessage = that.newwebsocketonmessage;
      //当websocket因为各种起因（失常或者异样）敞开之后，会调用onclose办法
      that.webNewSocket.onclose = that.newwebsocketclose;
      //当websocket因为异样起因（比方服务器部署、断网等）敞开之后，会调用onerror办法
      //在onerror中须要调用newreConnect办法重连服务器
      that.webNewSocket.onerror = that.newwebsocketonerror;
    },
    //打开
    newwebsocketonopen() {
      let that = this;
      console.log('websocket重新连接了')
      //连贯建设后批改标识
      that.isNewConnect = true;
      var userinfo = localStorage.getItem("userdata") || {}
      if(userinfo) {
      	userinfo = JSON.parse(userinfo)
      }
      var data = {
      	 'user_id': userinfo && (userinfo.uid + '-' + Math.floor(Math.random() * 10))  || "888-2",
      	 'iid': 1,
      };
      var msg = {
          'controller_name':'RoomController',
          'method_name':'bangding',
          'data':data
      };
      that.webNewSocket.send(JSON.stringify(msg));
      // 建设连贯后开始心跳
      // 因为nginx个别会设置例如60s没有传输数据就断开连接  所以要定时发送数据
      // that.timeoutObj = setTimeout(function() {
      //     if (that.isNewConnect) that.webNewSocket.send(that.checkMsg);
      // }, that.timeout);
    },
    newwebsocketonerror() {
      let that = this;
      console.log("webNewSocket服务出错了---onerror");
      //连贯断开后批改标识
      that.isNewConnect = false;

      //连贯谬误 须要重连
      that.newreConnect();
    },
    newwebsocketonmessage(e) {
      // 拿到数据，解决本人的业务
      let that = this;
      this.isNewConnect = true;
      clearTimeout(that.recnew);
      //处理设备报警信息
      that.init(e, that);
      //处理独自报警信息
      that.$init(e, that)
    },
    newwebsocketclose() {
      let that = this;
      console.log("webNewSocket服务关闭了+++onclose");
      //连贯断开后批改标识
      that.isNewConnect = false;
      that.newreConnect();
      clearTimeout(that.recnew);
    },
    newreConnect() {
      let that = this;
      console.log('尝试从新连贯',that.isNewConnect);
      //如果曾经连上就不在重连了
      if (that.isNewConnect) {
        clearTimeout(that.recnew);
        return false;
      } else {
        that.isNewConnect = true;
        clearTimeout(that.recnew);
        // 提早5秒重连  防止过屡次过频繁申请重连
        that.recnew = setTimeout(function() {
            that.createNewWebSocket();
        }, 5000);
      }

    },
    handleClosesy() {
      if(localStorage.getItem("syonoff") == 'on') {
        localStorage.setItem("syonoff", 'off')
        this.closeTitle = "打开声音"
      } else {
        localStorage.setItem("syonoff", 'on')
        this.closeTitle = "关闭声音"
      }
    },
    parseTime(time, cFormat) {
      if (arguments.length === 0) {
        return null;
      }
      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
          time = parseInt(time);
        }
        if (typeof time === "number" && time.toString().length === 10) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a") {
          return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return time_str;
    },
    //处理报警信息
    $init(res, _that) {
      let result = eval("(" + res.data + ")");
      if(!result){
        return false
      }
      if(result.route == 'device_warning') {
        let data = result.data;
        //报警器报警
        if(data.type == 2) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +"间报警器报警";
          } else {
          	location = "请注意查看，房间报警器报警";
          }
          this.$notice({
            message: "房间报警器报警",
            address: location,
            time: this.parseTime(data.time),
            duration: 60000,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //门磁报警
        if(data.type == 3) {
          let location = "";
          if(data.status == "on") {
            if(data.location) {
            	location = "请注意查看，"+ data.location +"间门打开";
            } else {
            	location = "请注意查看，卫生间门打开";
            }
          } else {
            if(data.location) {
            	location = data.location + "门关闭";
            } else {
            	location = "卫生间门关闭";
            }
          }

          this.$notice({
            message: "卫生间门状态",
            address: location,
            time: this.parseTime(data.time),
            duration: 60000,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //燃气报警器
        if(data.type == 4) {
          let location = "";
          if(data.location) {
          	location = data.location +"可燃气体报警";
          } else {
          	location = "请注意查看，房间可燃气体报警";
          }
          this.$notice({
            message: "可燃气体报警",
            address: location,
            time: this.parseTime(data.time),
            duration: 60000,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //人体红外传感器
        if(data.type == 5) {
          let location = "";
          if(data.status == 1) {
            if(data.location) {
            	location = "请注意查看，"+  data.location +"有人";
            } else {
            	location = "请注意查看，有人进入卫生间";
            }
          } else {
            if(data.location) {
            	location = data.location +"无人";
            } else {
            	location = "请注意查看，卫生间无人";
            }
          }

          this.$notice({
            message: "卫生间检测状态",
            address: location,
            time: this.parseTime(data.time),
            duration: 60000,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //烟雾报警器
        if(data.type == 6) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +" 烟雾报警";
          } else {
          	location = "请注意查看，房间烟雾报警";
          }
          this.$notice({
            message: "烟雾报警",
            address: location,
            time: this.parseTime(data.time),
            duration: 60000,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //漏水
        if(data.type == 8) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +"漏水报警";
          } else {
          	location = "请注意查看，房间漏水报警";
          }
          this.$notice({
            message: "漏水报警",
            address: location,
            time: this.parseTime(data.time),
            duration: 60000,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //漏水
        if(data.type == 10) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +"安防报警";
          } else {
          	location = "请注意查看，安防报警";
          }
          this.$notice({
            message: "安防报警",
            address: location || "安防报警",
            time: this.parseTime(data.time),
            duration: 60000,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //漏水
        if(data.type == 11) {
          data.status.forEach(function(item) {
          	if(item.id == 1) {
          		//在床
              if(item.value == 0) {
              	location = "";
              } else { //离床
              	location = "请注意查看，"+ data.location +"离床报警";
              }
          		if (location != "") {
                this.$notice({
                  message: "离床报警",
                  address: location || "离床报警",
                  time: this.parseTime(data.time),
                  duration: 60000,
                  onClick: () => {
                    data.log_id && iotLogupdate("get", {id: data.log_id})
                  }
                })
          		}
          	}
          	if(item.id == 2) {
          		//未尿床
          		let location = "";
          		if(item.value == 0) {
          			location = "";
          		} else { //尿湿
          			location = "请注意查看，"+ data.location +"尿湿报警";
          			if (location != ""){
                  this.$notice({
                    message: "尿湿报警",
                    address: location || "尿湿报警",
                    time: this.parseTime(data.time),
                    duration: 60000,
                    onClick: () => {
                      data.log_id && iotLogupdate("get", {id: data.log_id})
                    }
                  })
          			}
          		}
          	}
          })
        }

        if(data.type == 12) {
        	data.status.forEach(function(item) {
        		if(item.id == 2) {
        			//未尿床
        			let location = "";
        			if(item.value == 0) {
        				location = "";
        			} else { //尿湿
        				location = "请注意查看，"+ data.location +"尿湿报警";
        				if (location != ""){
        					this.$notice({
        					  message: "尿湿报警",
        					  address: location || "尿湿报警",
        					  time: this.parseTime(data.time),
        					  duration: 60000,
        					  onClick: () => {
        					    data.log_id && iotLogupdate("get", {id: data.log_id})
        					  }
        					})
        				}
        			}
        		}
        	})
        }
      }
    }
  }
}
